package io.persimmon.core.module.id.bo;

import io.persimmon.core.entity.DataRange;

public abstract class RangeBatchId implements BatchId<Long> {

    protected int batchSize;
    protected int index = 0;
    protected long minId = 0L;
    protected long maxId = 0L;


    public RangeBatchId(int batchSize) {
        if (batchSize < 1) {
            throw new IllegalArgumentException("size must be gte 1");
        }
        this.batchSize = batchSize;
    }

    @Override
    public Long nextId() {
        synchronized (RangeBatchId.class) {
            if (minId == maxId || minId + index > maxId) {
                DataRange<Long> dataRange = batchCreateId(this.batchSize);
                this.minId = dataRange.getMin();
                this.maxId = dataRange.getMax();
                this.index = 0;
            }
            return minId + index++;
        }
    }

    public abstract DataRange<Long> batchCreateId(int batchSize);
}
